package com.javasm.mb_store_api_final.adminLogin.login.admin;

import com.javasm.common.RedisKeys;

import com.javasm.mb_store_api_final.sys_control.usercontrol.sys_user.entity.SysUser;
import com.javasm.mb_store_api_final.sys_control.usercontrol.sys_user.service.SysUserService;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @Author: xmm
 * <p>
 * &#064;@Description:
 * <p>
 * &#064;@Date 2024/7/31 下午3:09
 */
@Component
public class AdminAuthenticationProvider implements AuthenticationProvider {

    @Resource(name = "adminLoginService1")
    UserDetailsService userDetailsService;

    @Resource
    SysUserService adminUserService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //PhoneLoginFilter中 存入的信息
        AdminAuthenticationToken token = (AdminAuthenticationToken) authentication;
        String username =  token.getPrincipal().toString();//用户名
        String password =  token.getCredentials().toString();//密码

        SysUser adminUser = adminUserService.getByUsername(username);
        if (adminUser == null) {
            throw new BadCredentialsException("用户不存在");
        }
        if (!password.equals(adminUser.getUserPassword())){
            throw new BadCredentialsException("密码错误");
        }
        //代码运行到这里,说明 密码 校验通过

        //根据 手机号,查询 用户信息
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        //组装成新的 PhoneAuthenticationToken
        //(用户信息,随意,权限列表)
        AdminAuthenticationToken authenticationToken = new AdminAuthenticationToken(userDetails,username,userDetails.getAuthorities());
        //详情  ip等等
        authenticationToken.setDetails(token.getDetails());
        return authenticationToken;
    }



    @Override
    public boolean supports(Class<?> aClass) {return AdminAuthenticationToken.class.isAssignableFrom(aClass);
    }
}
